package br.com.news.database.daos;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Named;

import org.hibernate.Query;

import br.com.news.database.daos.interfaces.IRespostaEnqueteDao;
import br.com.news.database.entities.AlternativaEnqueteEntity;
import br.com.news.database.entities.RespostaEnqueteEntity;
import br.com.news.database.exception.DataBaseException;
import br.com.news.database.utils.GenericDao;
import br.com.news.database.utils.HibernateUtility;

@Named
public class RespostaEnqueteDao extends GenericDao<RespostaEnqueteEntity, Long> implements IRespostaEnqueteDao{

	@SuppressWarnings("unchecked")
	@Override
	public List<RespostaEnqueteEntity> resultVoteXml(long idEnquete) throws DataBaseException {
		
		Query query1, query2;
		List<Object[]> objects = null;
		try {			
			query1 = getSession().createQuery(
					"select count(e), a"
				    + " from RespostaEnqueteEntity as e inner join e.alternativaEnquete as a"
					+ " where a.alternativaEnqueteKey.idEnquete = :idEnquete"
				    + " group by a.alternativaEnqueteKey.alternativa, a.descricao"
					);
	
			query1.setParameter("idEnquete", idEnquete);	
			
			List<RespostaEnqueteEntity> respostaEnqueteEntities = new ArrayList<RespostaEnqueteEntity>();
			
			if (query1.list().size() == 0) {
				query2 = HibernateUtility.getSession().createQuery(
						"select count(e), a"
					    + " from RespostaEnqueteEntity as e inner join e.alternativaEnquete as a"
						+ " where a.alternativaEnqueteKey.idEnquete = :idEnquete"
						);
				
				query2.setParameter("idEnquete", idEnquete);
				objects = query2.list();
			} else {
				objects = query1.list();
			}
			
			for(Object[] object : objects){
				RespostaEnqueteEntity respostaEnqueteEntity = new RespostaEnqueteEntity();
				respostaEnqueteEntity.setRowCount((Long)object[0]);
				respostaEnqueteEntity.setAlternativaEnquete((AlternativaEnqueteEntity)object[1]);
				respostaEnqueteEntities.add(respostaEnqueteEntity);
			}
			
			return respostaEnqueteEntities;
			
		} catch (Exception e) {
			throw new DataBaseException("Falha ao buscar resposta enquete!", e);
		}
	}
}
